from rest_framework import serializers
from home import models


class LevelThreeCategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = models.JobCategories
        fields = ['id', 'name', 'pid']  # 使用实际存在的字段


class LevelTwoCategorySerializer(serializers.ModelSerializer):
    children = LevelThreeCategorySerializer(many=True, read_only=True)

    class Meta:
        model = models.JobCategories
        fields = ['id', 'name', 'pid', 'children']


class JobCategoriesSerializerYi(serializers.ModelSerializer):
    children = LevelTwoCategorySerializer(many=True, read_only=True)

    class Meta:
        model = models.JobCategories
        fields = ['id', 'name', 'pid', 'children']


from rest_framework import serializers
from .models import Jobposting, JobCategories


class JobCategoriesSerializer(serializers.ModelSerializer):
    class Meta:
        model = JobCategories
        fields = '__all__'


class JobpostingSerializer(serializers.ModelSerializer):
    class Meta:
        model = Jobposting
        fields = '__all__'


from user import userser


class JobpostingSer(serializers.ModelSerializer):
    # 关联序列化，自动嵌套关联模型的数据
    city = userser.CitySerializer()
    hr = userser.HRInfoSerializer()
    company = userser.CompanySerializer()
    jobcate = JobCategoriesSerializer()

    class Meta:
        model = Jobposting
        fields = '__all__'


# 先定义 Jobposting 序列化器（避免循环依赖）


# 递归分类序列化器
class RecursiveJobCategoriesSer(serializers.ModelSerializer):
    """
    递归序列化器：处理 JobCategories 的自关联（children）
    """
    # 关键：用自身序列化器处理子分类，实现嵌套
    children = serializers.SerializerMethodField()
    # 关联招聘信息
    jobpostings = JobpostingSerializer(many=True, read_only=True)

    class Meta:
        model = JobCategories
        fields = ['id', 'name', 'children', 'jobpostings']

    def get_children(self, obj):
        """
        递归获取子分类：
        - 对每个子分类，再次调用当前序列化器
        - 实现一级 → 二级 → 三级的嵌套
        """
        # 子分类查询：利用模型的 related_name='children'
        children = obj.children.filter(pid=obj.id)  # 只查直接子分类（避免重复递归）
        # 递归序列化子分类
        return RecursiveJobCategoriesSer(children, many=True).data


class JobInfoSerializer(serializers.ModelSerializer):
    location_name = serializers.SerializerMethodField(read_only=True)

    def get_location_name(self, obj):
        return obj.company.location

    class Meta:
        model = models.Jobposting
        fields = '__all__'


class QuestionAnswerSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.QuestionAnswer
        fields = '__all__'


class QuestionAnswerInfoSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.QuestionAnswerInfo
        fields = '__all__'
